package com.erp.fin.controller;

import java.util.*;
import java.util.stream.Collectors;

import com.erp.common.controller.BaseController;
import com.erp.common.utils.*;
import com.erp.fin.domain.BillingDO;
import com.erp.itm.domain.PaytypeDO;
import com.erp.itm.service.PaytypeService;
import com.erp.oa.domain.NotifyDO;
import com.erp.oa.service.NotifyService;
import com.erp.pro.domain.InstockDO;
import com.erp.pur.domain.GroupDO;
import com.erp.pur.service.GroupService;
import com.erp.system.domain.CompanyDO;
import com.erp.system.domain.UserDO;
import com.erp.system.service.CompanyService;
import com.erp.system.service.UserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.erp.fin.domain.PaymentDO;
import com.erp.fin.service.PaymentService;

import javax.servlet.http.HttpServletResponse;

/**
 * 付款管理
 * 
 * @author Eric
 * @email shiliang900713@163.com
 * @date 2019-08-27 14:10:10
 */
 
@Controller
@RequestMapping("/fin/payment")
public class PaymentController extends BaseController {
	@Autowired
	private PaymentService paymentService;

	@Autowired
	private CompanyService companyService;

	@Autowired
	private GroupService groupService;

	@Autowired
	private PaytypeService paytypeService;

	@Autowired
	private UserService userService;
	@Autowired
	private NotifyService notifyService;
	
	@GetMapping()
	String Payment(){
	    return "fin/payment/payment";
	}

	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("fin:payment:payment")
	public PageUtils list(@RequestParam Map<String, Object> params){
		//查询列表数据
		PageUtils pageUtils = getPageUtils(params,null);
		return pageUtils;
	}



	@GetMapping("firstconfirm")
	String firstconfirm(){
		return "fin/payment/firstconfirm";
	}
	@ResponseBody
	@GetMapping("/firstconfirmlist")
	public PageUtils firstconfirmlist(@RequestParam Map<String, Object> params){
		//查询列表数据
		PageUtils pageUtils = getPageUtils(params,2);
		return pageUtils;
	}

	@GetMapping("secconfirm")
	String secconfirm(){
		return "fin/payment/secconfirm";
	}

	@ResponseBody
	@GetMapping("/secconfirmlist")
	public PageUtils secconfirmlist(@RequestParam Map<String, Object> params){
		//查询列表数据
		PageUtils pageUtils = getPageUtils(params,3);
		return pageUtils;
	}


	@GetMapping("/payment")
	String payment(){
		return "fin/payment/paymentlist";
	}

	@ResponseBody
	@GetMapping("/paymentlist")
	public PageUtils paymentlist(@RequestParam Map<String, Object> params){
		//查询列表数据
		PageUtils pageUtils = getPageUtils(params,4);
		return pageUtils;
	}


	private PageUtils getPageUtils(@RequestParam Map<String, Object> params,Integer status) {
		if(status != null){
			params.put("status",status);
		}
		//查询列表数据
		if(getUser().getDeptId() !=16){//财务和总经理技术可以看所有
			//查询是否是部门经理
			int mgrcount = userService.isManager(getUserId());
			if(mgrcount >0){//部门经理看到部门下所有人的和自己的
				params.put("depatmgr",getUser().getUserId());
			}else{
				params.put("userIdCreate",getUser().getUserId());
			}
		}


		Query query = new Query(params);
		List<PaymentDO> paymentList = paymentService.list(query);
		int total = paymentService.count(query);
		return new PageUtils(paymentList, total);
	}

	@GetMapping("/add")
	@RequiresPermissions("fin:payment:add")
	String add(){
	    return "fin/payment/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("fin:payment:edit")
	String edit(@PathVariable("id") Long id,Model model){
		PaymentDO payment = paymentService.get(id);
		model.addAttribute("payment", payment);
		List<GroupDO>  groupDOList = groupService.list(null);
		model.addAttribute("groupDOList", groupDOList);
		List<CompanyDO> companyDOList = companyService.list(null);
		model.addAttribute("companyDOList", companyDOList);
		List<PaytypeDO> paytypeList = paytypeService.list(null);
		model.addAttribute("paytypeList", paytypeList);
	    return "fin/payment/edit";
	}
	
	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("fin:payment:add")
	public R save( PaymentDO payment){
		payment.setUserIdCreate(getUserId());
		payment.setUserNameCreate(getUser().getName());
		payment.setGmtCreate(new Date());
		payment.setStatus(1);
		//查询合同编号
		setinfo(payment);
		if(paymentService.save(payment)>0){
			return R.ok();
		}
		return R.error();
	}
	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("fin:payment:edit")
	public R update( PaymentDO payment){
		setinfo(payment);
		paymentService.update(payment);
		return R.ok();
	}

	private void setinfo(PaymentDO payment) {
		//查询合同编号
		GroupDO groupDO = groupService.get(payment.getPurId());
		if (groupDO != null) {
			payment.setPurGroupid(groupDO.getGroupid());
		}
		//查询付款方
		CompanyDO companyDO = companyService.get(Integer.parseInt(payment.getPaymentComid() + ""));
		if (companyDO != null) {
			payment.setPaymentName(companyDO.getName());
		}
		//查询付款方式
		PaytypeDO paytypeDO = paytypeService.get(payment.getPaymentTypeid());
		if (paytypeDO != null) {
			payment.setPaymentType(paytypeDO.getName());
		}

		if(payment.getDepetLeaderid() !=null){
			UserDO userDO = userService.get(payment.getDepetLeaderid());
			payment.setDepetLeadername(userDO.getName());
		}
	}

	/**
	 * 删除
	 */
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("fin:payment:remove")
	public R remove( Long id){
		if(paymentService.remove(id)>0){
		return R.ok();
		}
		return R.error();
	}


	/**
	 * 初审
	 * @param id
	 * @return
	 */
	@PostMapping( "/confirmfirst")
	@ResponseBody
	public R confirmfirst(Long id){
		if(paymentService.confirmfirst(id)>0){
			PaymentDO paymentDO = paymentService.get(id);
			//通知
			//发通知和邮件通知采购和总经理
			NotifyDO notify = new NotifyDO();
			notify.setType("7");
			notify.setTitle("付款申请");
			notify.setContent("采购合同编号为["+paymentDO.getPurGroupid()+"]，金额为["+paymentDO.getAppliAmount()+"]申请付款审核");
			Long[] userIds =new Long[]{paymentDO.getDepetLeaderid()};
			notify.setUserIds(userIds);
			notify.setStatus("1");
			notify.setCreateBy(getUserId());
			notifyService.save(notify);
			return R.ok("确认提交成功");
		}
		return R.error("确认提交失败");
	}


	/**
	 * 初审通过
	 */
	@PostMapping( "/reviewyes")
	@ResponseBody
	public R reviewyes( Long id){
		if(paymentService.reviewyes(id)>0){
			PaymentDO paymentDO = paymentService.get(id);
			//通知
			//发通知和邮件通知采购和总经理
			NotifyDO notify = new NotifyDO();
			notify.setType("7");
			notify.setTitle("付款申请");
			List<Long> deprids = new ArrayList<>();
			deprids.add(16L);
			List<UserDO> userDOList =userService.getUsersByDeptIds(deprids);
			List<Long> userId = userDOList.stream().map(UserDO::getUserId).collect(Collectors.toList());
			notify.setContent("采购合同编号为["+paymentDO.getPurGroupid()+"]，金额为["+paymentDO.getAppliAmount()+"]付款申请初步审核通过了,请及做二次审核");
			Long[] userIds =userIds = userId.toArray( new Long[userId.size()]);
			notify.setUserIds(userIds);
			notify.setStatus("1");
			notify.setCreateBy(getUserId());
			notifyService.save(notify);
			return R.ok("初审通过操作成功");
		}
		return R.error("初审通过操作失败，请重新操作");
	}
	/**
	 * 初审不通过
	 */
	@PostMapping( "/reviewno")
	@ResponseBody
	public R reviewno( Long id){
		if(paymentService.reviewno(id)>0){
			PaymentDO paymentDO = paymentService.get(id);
			//通知
			//发通知和邮件通知采购和总经理
			NotifyDO notify = new NotifyDO();
			notify.setType("7");
			notify.setTitle("付款申请");
			notify.setContent("采购合同编号为["+paymentDO.getPurGroupid()+"]，金额为["+paymentDO.getAppliAmount()+"]付款申请初步审核被拒绝了");
			Long[] userIds =new Long[]{paymentDO.getUserIdCreate()};
			notify.setUserIds(userIds);
			notify.setStatus("1");
			notify.setCreateBy(getUserId());
			notifyService.save(notify);
			return R.ok("初审拒绝操作成功");
		}
		return R.error("初审拒绝操作失败，请重新操作");
	}

	/**
	 * 终审通过
	 */
	@PostMapping( "/seccondyes")
	@ResponseBody
	public R seccondyes( Long id){
		if(paymentService.seccondyes(id)>0){
			PaymentDO paymentDO = paymentService.get(id);
			//通知
			//发通知和邮件通知采购和总经理
			NotifyDO notify = new NotifyDO();
			notify.setType("7");
			notify.setTitle("付款申请");
			List<Long> deprids = new ArrayList<>();
			deprids.add(23L);
			List<UserDO> userDOList =userService.getUsersByDeptIds(deprids);
			List<Long> userId = userDOList.stream().map(UserDO::getUserId).collect(Collectors.toList());
			notify.setContent("采购合同编号为["+paymentDO.getPurGroupid()+"]，金额为["+paymentDO.getAppliAmount()+"]付款申请审核通过了,请及时安排付款");
			Long[] userIds =userIds = userId.toArray( new Long[userId.size()]);
			notify.setUserIds(userIds);
			notify.setStatus("1");
			notify.setCreateBy(getUserId());
			notifyService.save(notify);
			return R.ok("终审通过操作成功");
		}
		return R.error("初审通过操作失败，请重新操作");
	}
	/**
	 * 终审不通过
	 */
	@PostMapping( "/seccondno")
	@ResponseBody
	public R seccondno( Long id){
		if(paymentService.seccondno(id)>0){
			PaymentDO paymentDO = paymentService.get(id);
			//通知
			//发通知和邮件通知采购和总经理
			NotifyDO notify = new NotifyDO();
			notify.setType("7");
			notify.setTitle("付款申请");
			notify.setContent("采购合同编号为["+paymentDO.getPurGroupid()+"]，金额为["+paymentDO.getAppliAmount()+"]付款申请终审被拒绝了");
			Long[] userIds =new Long[]{paymentDO.getUserIdCreate()};
			notify.setUserIds(userIds);
			notify.setStatus("1");
			notify.setCreateBy(getUserId());
			notifyService.save(notify);
			return R.ok("终审拒绝操作成功");
		}
		return R.error("终审拒绝操作失败，请重新操作");
	}

	@GetMapping("/paymentedit/{id}")
	String paymentedit(@PathVariable("id") Long id,Model model){
		PaymentDO payment = paymentService.get(id);
		model.addAttribute("payment", payment);
		return "fin/payment/paymentedit";
	}

	/**
	 * 付款
	 */
	@PostMapping("/payment")
	@ResponseBody
	public R payment( PaymentDO payment){
		//查询基本信息
		PaymentDO paymentDO = paymentService.get(payment.getId());
		//先更新采购合同的已付金额
		int num = groupService.updatePaymentPrice(paymentDO.getPurId(),paymentDO.getAppliAmount());
		if(num >0){
			if(paymentService.payment(payment)>0){
				return R.ok("付款成功");
			}
		}
		return R.error("付款失败");
	}
	@GetMapping("/getPaymentByPur/{id}")
	String getPaymentByPurInHtml(@PathVariable("id") Long id,Model model){
		model.addAttribute("purId", id);
		return "fin/payment/getPaymentByPur";
	}

	@PostMapping("/exportData")
	@ResponseBody
	public void downloadTemplate(PaymentDO payment, HttpServletResponse response){
		//ProjectDO project
		Map<String, Object> params = new HashMap<>();
		if(StringUtils.isNotBlank(payment.getPurGroupid())){
			params.put("purGroupid",payment.getPurGroupid());
		}
		if(StringUtils.isNotBlank(payment.getDepetLeadername())){
			params.put("depetLeadername",payment.getDepetLeadername());
		}
		if(StringUtils.isNotBlank(payment.getPayee())){
			params.put("payee",payment.getPayee());
		}
		if(StringUtils.isNotBlank(payment.getPaymentName())){
			params.put("paymentName",payment.getPaymentName());
		}
		if(payment.getPayDateStr() != null){
			params.put("payDateStr",payment.getPayDateStr());
		}
		if(payment.getPayDateend() != null){
			params.put("payDateend",payment.getPayDateend());
		}
		List<PaymentDO> paymentDOList = paymentService.list(params);
		ExcelUtil.exportExcel(paymentDOList,"付款记录","付款记录",PaymentDO.class,"付款记录.xls",response);
	}
}
